package code.producerandconsumer;

import java.util.concurrent.BlockingQueue;

public class Producer implements Runnable {
    private final BlockingQueue<Integer> queue;
    private final int MAX_SIZE = 5;

    public Producer(BlockingQueue<Integer> queue) {
        this.queue = queue;
    }


    @Override
    public void run() {
        for(int i=1; i<=10; i++) {
            try {
                produce(i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void produce(int i) throws InterruptedException {
        synchronized (queue) {
            while (queue.size() == MAX_SIZE) {
                System.out.println("缓冲区已满，⽣产者等待...");
                queue.wait();
            }
            queue.put(i);
            System.out.println("⽣产者⽣产物品：" + i);
            queue.notifyAll();  // 唤醒所有等待的消费者线程
        }
    }
}
